<template>
  <div class="section-page" v-if="section">
    <div class="section-header">
      <h2>{{ section.name }}</h2>
      <p>{{ section.description || '暂无描述' }}</p>
      <div class="section-info">
        <span>创建时间: {{ section.created_at || '未知' }}</span>
      </div>
      <button @click="showCreatePostModal" class="btn create-post-btn">发表新帖</button>
    </div>

    <div class="posts-container">
      <div class="post-card" v-for="post in posts" :key="post.post_id">
        <div class="post-header">
          <span class="post-author">用户ID: {{ post.author_id }}</span>
          <span class="post-time">{{ post.created_at || '未知时间' }}</span>
        </div>
        <div class="post-content">
          {{ post.content }}
        </div>
      </div>

      <div class="no-posts" v-if="posts.length === 0">
        <p>暂无帖子，快来发表第一个帖子吧！</p>
      </div>
    </div>

    <!-- 发表帖子模态框 -->
    <div class="modal-overlay" v-if="showPostModal" @click="closePostModal">
      <div class="modal-container" @click.stop>
        <div class="modal-header">
          <h2>发表新帖</h2>
          <span class="close" @click="closePostModal">&times;</span>
        </div>
        <div class="modal-body">
          <form @submit.prevent="createPost" class="post-form">
            <div class="form-group">
              <label for="postContent">帖子内容</label>
              <textarea 
                id="postContent" 
                v-model="newPost.content" 
                required
                placeholder="请输入帖子内容"
                class="form-textarea">
              </textarea>
            </div>
            <div class="form-actions">
              <button type="submit" class="submit-btn">发表</button>
              <button type="button" @click="closePostModal" class="cancel-btn">取消</button>
            </div>
          </form>
          <Alert 
            v-if="postMessage"
            :type="postMessageType"
            :description="postMessage"
            :closable="false"
            v-model="postAlertVisible"
          />
        </div>
      </div>
    </div>
  </div>

  <div class="section-not-found" v-else>
    <h2>板块不存在</h2>
    <p>找不到指定的板块</p>
    <router-link to="/sections" class="btn back-btn">返回板块列表</router-link>
  </div>
</template>

<script>
import Alert from '@/components/Alert.vue';

export default {
  name: 'Section',
  components: {
    Alert
  },
  data() {
    return {
      section: null,
      posts: [],
      currentUser: null,
      showPostModal: false,
      newPost: {
        content: ''
      },
      postMessage: '',
      postMessageType: '',
      postAlertVisible: true
    }
  },
  mounted() {
    this.loadSection();
    this.loadPosts();
    this.checkLoginStatus();
  },
  methods: {
    checkLoginStatus() {
      const user = localStorage.getItem('user');
      if (user) {
        this.currentUser = JSON.parse(user);
      }
    },
    async loadSection() {
      try {
        const sectionId = this.$route.params.id;
        const response = await fetch(`http://127.0.0.1:11451/sections/`);
        if (response.ok) {
          const sections = await response.json();
          this.section = sections.find(s => s.section_id == sectionId) || null;
        }
      } catch (error) {
        console.error('加载板块信息失败:', error);
      }
    },
    async loadPosts() {
      try {
        const sectionId = this.$route.params.id;
        const response = await fetch(`http://127.0.0.1:11451/posts/?section_id=${sectionId}`);
        if (response.ok) {
          this.posts = await response.json();
        }
      } catch (error) {
        console.error('加载帖子列表失败:', error);
      }
    },
    showCreatePostModal() {
      if (!this.currentUser) {
        alert('请先登录');
        this.$eventBus.emit('open-login');
        return;
      }
      this.showPostModal = true;
      this.newPost = {
        content: '',
        section_id: parseInt(this.$route.params.id)
      };
      this.postMessage = '';
      this.postMessageType = '';
      this.postAlertVisible = true;
    },
    closePostModal() {
      this.showPostModal = false;
    },
    async createPost() {
      try {
        const response = await fetch(`http://127.0.0.1:11451/posts/?user_id=${this.currentUser.user_id}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(this.newPost)
        });

        if (response.ok) {
          const post = await response.json();
          this.posts.unshift(post); // 将新帖子添加到列表开头
          this.postMessage = '帖子发表成功';
          this.postMessageType = 'success';
          this.postAlertVisible = true;
          
          // 1秒后关闭模态框
          setTimeout(() => {
            this.closePostModal();
            this.newPost.content = ''; // 清空内容
          }, 1000);
        } else {
          const error = await response.json();
          this.postMessage = error.detail || '发表帖子失败';
          this.postMessageType = 'error';
          this.postAlertVisible = true;
        }
      } catch (error) {
        this.postMessage = '发表帖子过程中发生错误: ' + error.message;
        this.postMessageType = 'error';
        this.postAlertVisible = true;
      }
    }
  }
}
</script>

<style scoped>
.section-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.section-header {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 25px;
  margin-bottom: 30px;
}

.section-header h2 {
  margin: 0 0 10px 0;
  color: #007bff;
}

.section-header p {
  color: #666;
  margin-bottom: 15px;
}

.section-info {
  font-size: 14px;
  color: #999;
}

.post-actions {
  margin-bottom: 30px;
  text-align: right;
}

.create-post-btn {
  background-color: #28a745;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.create-post-btn:hover {
  background-color: #218838;
}

.posts-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.post-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.post-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.post-author {
  font-weight: bold;
  color: #007bff;
}

.post-time {
  font-size: 12px;
  color: #999;
}

.post-content {
  white-space: pre-wrap;
  line-height: 1.6;
}

.no-posts {
  text-align: center;
  padding: 50px 0;
  color: #666;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-container {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  width: 90%;
  max-width: 600px;
  overflow: hidden;
  animation: modalFadeIn 0.3s ease-out;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  padding: 20px;
  background: linear-gradient(135deg, #28a745, #218838);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h2 {
  margin: 0;
  font-size: 1.5rem;
}

.close {
  color: white;
  font-size: 28px;
  font-weight: bold;
  cursor: pointer;
  transition: transform 0.2s;
}

.close:hover {
  transform: scale(1.1);
}

.modal-body {
  padding: 25px;
}

.post-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #333;
}

.form-textarea {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  box-sizing: border-box;
  transition: border-color 0.3s, box-shadow 0.3s;
  min-height: 150px;
  resize: vertical;
}

.form-textarea:focus {
  outline: none;
  border-color: #28a745;
  box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.1);
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.submit-btn, .cancel-btn {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: transform 0.2s, box-shadow 0.2s;
}

.submit-btn {
  background-color: #28a745;
  color: white;
}

.submit-btn:hover {
  background-color: #218838;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.cancel-btn {
  background-color: #6c757d;
  color: white;
}

.cancel-btn:hover {
  background-color: #545b62;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.message {
  padding: 12px;
  border-radius: 6px;
  margin-top: 15px;
  text-align: center;
  font-weight: 500;
}

.message.success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.message.error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.section-not-found {
  text-align: center;
  padding: 50px 20px;
}

.back-btn {
  display: inline-block;
  background-color: #007bff;
  color: white;
  text-decoration: none;
  padding: 10px 20px;
  border-radius: 4px;
  margin-top: 20px;
}

.back-btn:hover {
  background-color: #0056b3;
}

@media (max-width: 768px) {
  .section-page {
    padding: 10px;
  }
  
  .post-header {
    flex-direction: column;
    gap: 5px;
    align-items: flex-start;
  }
}
</style>